<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/4/11
 * Time: 22:43
 */

namespace Org;


class Weixin
{

    private $appid;

    private $appsecret;

    private $mchid;

    private $wechatkey;



    private $token;

    public function __construct()
    {

        $this->appid = C('appid');
        $this->appsecret = C("appsecret");
        $this->mchid = C("mchid");
        $this->wechatkey = C("wechatkey");
        $this->token = C('token');

    }



    public function chushi()
    {
        echo  $this->getaccesstoken();
    }

    public function checkSignature()
    {

        $signature = $_GET['signature'];
        $timestamp = $_GET['timestamp'];
        $nonce = $_GET['nonce'];
        $token = $this->token;
        $arrtemp = array($token, $timestamp, $nonce);
        sort($arrtemp, SORT_STRING);
        $arrtemp = implode($arrtemp);
        $arrtemp = sha1($arrtemp);
        if ($arrtemp == $signature) {


            return true;

        } else {

            return false;
        }

    }

    public function valid()
    {


        $echoStr = $_GET['echostr'];
        if ($this->checkSignature()) {

            echo $echoStr;
            exit;
        }
    }
//根据返回的信息,做出相应的处理
    public function responseMsg()
    {

        $postStr = file_get_contents('php://input');


        if (!empty($postStr)){
            /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
               the best way is to check the validity of xml by yourself */
            libxml_disable_entity_loader(true);
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $fromUsername = $postObj->FromUserName;
            $toUsername = $postObj->ToUserName;
            $keyword = trim($postObj->Content);
            $time = time();
            $textTpl = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Content><![CDATA[%s]]></Content>
							<FuncFlag>0</FuncFlag>
							</xml>";
            if(!empty( $keyword ))
            {
                $msgType = "text";
                $contentStr = "Welcome to wechat world!";
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                echo $resultStr;
            }else{
                echo "Input something...";
            }

        }else {
            echo "";
            exit;
        }
    }

    public function getaccesstoken()
    {

           $access_token = S('access_token');
        if(!empty($access_token)){

            return $access_token;

        }else{

            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $this->appid . "&secret=" . $this->appsecret;;

            $ret = $this->curlget($url);

            $ret = json_decode($ret,true);
            S('access_token',$ret['access_token'],7100);
            return $ret['access_token'];

        }

    }
    function p($arr){


        echo "<meta charset='utf8'><pre>";
        print_r($arr);
    }

    function curlget($url)
    {


        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;

    }

    public function jingmo($url,$code,$state){
        echo "<meta charset='utf8'>";
        if($code){
             $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->appid."&secret=".$this->appsecret."&code=".$code."&grant_type=authorization_code";
             $arrtemp = json_decode($this->curlget($url),true);
             $ret = $this->getuserinfo($arrtemp['openid'],$arrtemp['access_token']);
            return  $ret;
        }else{

            $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->appid."&redirect_uri=".$url."&response_type=code&scope=snsapi_base&state=".$state."#wechat_redirect";

            header("Location: $url");
        }



    }

    public function getuserinfo($openid,$user_access_token){


        $userurl = "https://api.weixin.qq.com/sns/userinfo?access_token=".$user_access_token."&openid=".$openid."&lang=zh_CN";

        $userinfo = json_decode($this->curlget($userurl),true);
        return $userinfo;

    }

    public function getjsapi_ticket(){


        $js_ticket = S("js_ticket");
        if(!empty($js_ticket)){

            return $js_ticket;
        }else{

            $access_token = $this->getaccesstoken();
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$access_token."&type=jsapi";
            $res = json_decode($this->curlget($url),true);
            S("js_ticket",$res['ticket'],7100);

            return $res['ticket'];
        }


    }

    public function getjssign(){
        echo "<meta charset='utf8'>";

        $js_ticket = $this->getjsapi_ticket();
        $time = time();

        $arr = array(

            'noncestr'=>md5($time),
            'jsapi_ticket'=>$js_ticket,
            'timestamp'=>$time,
            'url'=>'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'],


        );
        $this->p($arr);
        ksort($arr);
        $string="";
        $i=1;
        foreach($arr as $key=>$val){

             if($i==1){

                 $string.=$key."=".$val;
             }else{
                 $string.="&".$key."=".$val;

             }

          $i++;
            echo $i;
        }

        echo $string;
        $signature =strtolower($string);
        $signature =  sha1($string);

        $jsconfig = array(
            'debug'=>true,

            'appId'=>$this->appid,
            'timestamp'=>$time,
            'nonceStr'=>md5($time),
            'signature'=>$signature,
            ' jsApiList'=>"['onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ']",
        );
        $json = json_encode($jsconfig);

       return $json;

    }

    //支付
    public function getpaysign(){



        $time = time();

      $arr = array(

          'appid'=>$this->appid,
          'mch_id'=>$this->mchid,
          'nonce_str'=>md5($time),
          '	body'=>"sdf",
          'out_trade_no'=>"2016".$time,
          'total_fee'=>1,
          'spbill_create_ip'=>"127.0.0.1",
          'notify_url'=>"http://www.baidu.com",
          'trade_type'=>"JSAPI",
      );

        ksort($arr);
        $string="";
        $i=1;
        foreach($arr as $key=>$val){

            if($i==1){

                $string.=$key."=".$val;
            }else{
                $string.="&".$key."=".$val;

            }

            $i++;

        }



        $string.="&key=".$this->wechatkey;
        $sign = strtoupper(md5($string));



       $arr['sign'] = $sign;

        return $arr;


    }

    function Post($curlPost,$url){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_NOBODY, true);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        $return_str = curl_exec($curl);
        curl_close($curl);
        return $return_str;
    }







}